package com.ruoyi.cderp.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.cderp.config.TencentCosConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

// OSS服务工具类
@Service
public class OssService {
    @Autowired
    private COSClient cosClient;

    @Autowired
    private TencentCosConfig cosConfig;

    public String uploadFile(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + fileExt;

        // 设置文件元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());

        // 上传文件
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                cosConfig.getBucketName(),
                newFileName,
                file.getInputStream(),
                metadata
        );

        cosClient.putObject(putObjectRequest);

        // 返回文件访问URL
        return "https://" + cosConfig.getBucketName() +
                ".cos." + cosConfig.getRegion() +
                ".myqcloud.com/" + newFileName;
    }
}
